﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMS.HelperClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using WHMS.HelperClasses;
using WHMS.EntityClasses;
using WHMS.TypedViewClasses;

namespace WMS
{
    public partial class InitialBalanceForm : Form
    {

        bool IsAdmin=false;

        public InitialBalanceForm()
        {
            InitializeComponent();

            LoadData();
        }

        void LoadData()
        {
            //Get the user role of current user,to determine whether to show all projects(for admin or executive manager) or only projects without transactions(for everyone else)
            int userid = Business.GetCurrentUserId();
            EntityCollection<UserEntity> user = new EntityCollection<UserEntity>();
            RelationPredicateBucket filter = new RelationPredicateBucket(UserFields.Id == userid);
            DALHelper.FetchCollection(user, filter);

            EntityCollection<UserRoleEntity> userrole = new EntityCollection<UserRoleEntity>();
            filter = new RelationPredicateBucket(UserRoleFields.UserId == userid);
            DALHelper.FetchCollection(userrole, filter);


            if (userrole.Count > 0)
            {
                for (int i = 0; i < userrole.Count; i++)
                    if (userrole[i].RoleId == 4 || userrole[i].RoleId == 5)//User role admin or executive manager
                    {
                        IsAdmin = true;
                        break;
                    }

            }

            DALHelper.FetchCollection(_projects);

            ResetTransactionItems();
            GetShelves();
            

            //if (IsAdmin)
            //        FormsHelper.LoadComboBox(StoresDDL, StoreFields.Id, StoreFields.Name, () => DALHelper.GetDynamicList(StoreFields.Id, StoreFields.Name, null));
            //    else
            //        FormsHelper.LoadComboBox(StoresDDL, StoreFields.Id, StoreFields.Name, () => Business.GetStoresWithoutTransactions());

            //Business.GetItemview(_items);//DALHelper.FetchCollection(_items);

            //FormsHelper.CheckStoresAndProjects(StoresDDL.Items, _projects, new List<Control>() { dataGridView1, SaveBtn }, NoStoresLbl, NoProjectsLbl);

        }

        private int GetSelectedStoreId()
        {
            DataTable DTStore = Business.GetStoreDetails(StoresTB.Text);
            if (DTStore.Rows.Count > 0)
            {
                return Int32.Parse(DTStore.Rows[0][0].ToString());
            }

            return 0;
        }

        private int GetSelectedProjectId()
        {
            ProjectEntity project = Business.GetProjectByCode(txtProjectCode.Text);
            if (project != null)
            {
                return project.Id;
            }

            return 0;
        }
        private void GetShelves()
        {
            var storeId = GetSelectedStoreId();
            _shelves.Clear();
            var filter = new RelationPredicateBucket();
            if (storeId > 0)
            {
                filter.PredicateExpression.Add(ShelfFields.StoreId == storeId);
            }

            DALHelper.FetchCollection(_shelves, new RelationPredicateBucket(ShelfFields.StoreId == storeId));


        }

        //private void StoresDDL_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    ResetTransactionItems();

        //    if (StoresDDL.SelectedItem == null)
        //        return;

        //    GetShelves();
        //}

        DataMngrFormBase<InitialBalanceEntity> _storeBalanceForm;
        private void ResetTransactionItems()
        {
            if (_storeBalanceForm != null)
            {
                _storeBalanceForm.Dispose();
                _storeBalanceForm = null;
            }

            var label = new Label();
            var filter = new RelationPredicateBucket(InitialBalanceFields.StoreId == GetSelectedStoreId());
           // var prefetch = new PrefetchPath2(
            PrefetchPath2 prefetchPath = new PrefetchPath2(WHMS.EntityType.InitialBalanceEntity);
            prefetchPath.Add(InitialBalanceEntity.PrefetchPathShelf);

            
            int projectId = 0;
            if (!string.IsNullOrWhiteSpace(txtProjectCode.Text))
            {
                // i dont know what the _project is but it contains all the projecst so I got the project with the right code, the user choose
                var project = _projects.Cast<ProjectEntity>().FirstOrDefault(x => x.Code == txtProjectCode.Text);
                if (project != null)
                {
                    projectId = project.Id;
                }
            }

            filter.PredicateExpression.Add(InitialBalanceFields.ProjectId == projectId);
            _storeBalanceForm = new DataMngrFormBase<InitialBalanceEntity>(InitialBalance, dataGridView1, InitialBalanceBS, SaveBtn, SaveResult, DeleteResult, filter, prefetchPath, true, NextPageBtn, PrevPageBtn);

            _storeBalanceForm.SetNumericFields(new List<int> { 2, 3 });
            _storeBalanceForm.SetMandatoryFields(new List<int> { 0, 1, 2, 3 });
            //_storeBalanceForm.RaiseSelectedChangedEventForComboBoxColumns(new List<int> { 1 });
            _storeBalanceForm.ComboboxColumnSelectionChanged += new DataMngrFormBase<InitialBalanceEntity>.RaiseComboboxColumnSelectionChanged(_storeBalanceForm_ComboboxColumnSelectionChanged);
            _storeBalanceForm.BeforeSave += new DataMngrFormBase<InitialBalanceEntity>.RaiseBeforeSave(_storeBalanceForm_BeforeSave);
        }

        void _storeBalanceForm_BeforeSave(IEntityCollection2 collectionToBeSaved)
        {
            if (string.IsNullOrWhiteSpace(txtProjectCode.Text))
            {
                errLblProjectCodeIsRequired.Visible = true;
                return;
            }
            foreach (InitialBalanceEntity entity in collectionToBeSaved)
            {
                entity.StoreId = GetSelectedStoreId();

                // this add cause it will handel the missing of the ProjectId in the entitiy
                if (!string.IsNullOrWhiteSpace(txtProjectCode.Text))
                {
                    // i dont know what the _project is but it contains all the projecst so I got the project with the right code, the user choose
                    var project = _projects.Cast<ProjectEntity>().FirstOrDefault(x => x.Code == txtProjectCode.Text);
                    if (project != null)
                    {
                        entity.ProjectId = project.Id;
                        entity.Project = project;
    
                    }
                }

                if (entity.CurrentBalance == null)
                    entity.CurrentBalance = entity.Balance;
            }
        }

        void _storeBalanceForm_ComboboxColumnSelectionChanged(object selectedValue)
        {
            //if (selectedValue == null)
            //    return;

            //if (selectedValue is int)
            //{
            //    if (dataGridView1.CurrentCell.ColumnIndex == 1)
            //    {
            //        Business.GetItemsPlannedForProject((int)selectedValue, _items);
            //    }
            //}
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;

            //if (e.ColumnIndex == projectIdDataGridViewTextBoxColumn.Index)
            //{				
            //    LoadItems(e.RowIndex);
            //}
        }

        //private void LoadItems(int rowIndex)
        //{
        //var projectId = dataGridView1.CurrentRow.Cells[projectIdDataGridViewTextBoxColumn.Index].Value;
        //if (projectId == null)
        //    return;

        //var control = (dataGridView1[itemIdDataGridViewTextBoxColumn.Index, rowIndex] as DataGridViewComboBoxCell);

        //var items = new ItemViewTypedView();
        //Business.GetItemsPlannedForProject((int)projectId, items);

        //var bindingsource = new BindingSource();
        //bindingsource.DataSource = items;
        //control.DataSource = bindingsource;
        //control.DisplayMember = ItemViewFields.NameCodeUnit.Name;
        //control.ValueMember = ItemViewFields.Id.Name;

        //if (items.Count <= 0)
        //{
        //    MessageBox.Show("لا يوجد أصناف فى خطة المشروع المختار", "تنبيه", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //}
        //}

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != balanceDataGridViewTextBoxColumn.Index)
                return;

            var itemIdValue = dataGridView1.Rows[e.RowIndex].Cells[ItemId.Index].Value;
            if (itemIdValue == null)
                return;

            var form = new UnitConverterForm((int)itemIdValue);
            if (form.ShowDialog() == DialogResult.OK)
            {
                dataGridView1.SuspendLayout();
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.Value;
                dataGridView1.UpdateCellValue(e.ColumnIndex, e.RowIndex);
                dataGridView1.ResumeLayout(true);
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == ItemCode.Index)
            {
                if(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value!=null)
                {
                var dt = Business.GetItemDetails(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());

                if (dt.Rows.Count <= 0)
                    return;

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.Rows[i].Cells[ItemId.Index].Value != null &&
                        (int)dataGridView1.Rows[i].Cells[ItemId.Index].Value == (int)dt.Rows[0][0])
                    {
                        MessageBox.Show("تم اضافة هذا الصنف من قبل", "خطأ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        dataGridView1.Rows.RemoveAt(e.RowIndex);
                        return;
                    }
                }

                dataGridView1.Rows[e.RowIndex].Cells[ItemId.Index].Value = (int)dt.Rows[0][0];
                dataGridView1.Rows[e.RowIndex].Cells[ItemName.Index].Value = (string)dt.Rows[0][1];
                dataGridView1.Rows[e.RowIndex].Cells[ItemUnit.Index].Value = (string)dt.Rows[0][2];
                }
            }
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                var item = (InitialBalanceEntity)row.DataBoundItem;
                if (item == null)
                    continue;

                var dt = Business.GetItemDetails(item.ItemId);
                if (dt.Rows.Count <= 0)
                    continue;

                row.Cells[ItemCode.Index].Value = (string)dt.Rows[0][0];
                row.Cells[ItemName.Index].Value = (string)dt.Rows[0][1];
                row.Cells[ItemUnit.Index].Value = (string)dt.Rows[0][2];
            }
        }

        // this event occures whenever a key is pressed
        private void txtProjectCode_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyValue != (int)Keys.Enter) return;
            LoadProject();

        }
        private void LoadProject()
        {
            // i'm only interrested in the Enter key, if any other key is pressed do nothing

            if (!string.IsNullOrWhiteSpace(txtProjectCode.Text))
            {
                // i dont know what the _project is but it contains all the projecst so I got the project with the right code, the user choose
                var project = _projects.Cast<ProjectEntity>().FirstOrDefault(x => x.Code == txtProjectCode.Text);
                if (project != null)
                {
                    txtProjectCode.Text = project.Code;
                    lblProjectName.Text = project.Name;
                    lblProjectDescription.Text = project.Status;
                    errLblProjectNotFound.Visible = false;
                    errLblProjectCodeIsRequired.Visible = false;
                    // project is changed, so all the items should be cleard , shouldn't they?
                    ResetTransactionItems();

                    if (string.IsNullOrEmpty(StoresTB.Text))
                    {
                        return;
                    }

                    GetShelves();
                    return; // every thing is done fine, so return
                }
                else
                {
                    // if the code entered is not a valid code  
                    lblProjectDescription.Visible = false;
                    errLblProjectNotFound.Visible = true;
                    lblProjectName.Text = string.Empty;
                }
            }
            else
            {
                lblProjectDescription.Visible = false;
                errLblProjectNotFound.Visible = false;
                lblProjectName.Text = string.Empty;
            }
        }
        private void txtProjectCode_TextChanged(object sender, EventArgs e)
        {
            LoadProject();
        }

        private void SearchNameBtn_Click(object sender, EventArgs e)
        {
            int projectId = 0;
            var storeId = GetSelectedStoreId();


            var filter = new PredicateExpression();
            if (storeId > 0)
            {
                filter.Add(StoreShelfBalanceFields.StoreId == storeId);
            }

            if (!string.IsNullOrWhiteSpace(txtProjectCode.Text))
            {
                var project = _projects.Cast<ProjectEntity>().FirstOrDefault(x => x.Code == txtProjectCode.Text);
                if (project != null)
                {
                    projectId = project.Id;
                    filter.AddWithAnd(StoreShelfBalanceFields.ProjectId == projectId);
                }
            }


            var itemPickerForm = new ItemPickerForm(1, 1, filter);
            if (itemPickerForm.ShowDialog() == DialogResult.OK)
            {
                if (itemPickerForm.SelectedItemId == 0)
                    return;

                var filter2 = new RelationPredicateBucket(StoreShelfBalanceFields.ItemId == itemPickerForm.SelectedItemId);
                filter2.Relations.Add(StoreShelfBalanceEntity.Relations.ShelfEntityUsingShelfId);
                filter2.PredicateExpression.AddWithAnd(filter);
                StoreShelfBalance.Clear();
                DALHelper.FetchCollection(StoreShelfBalance, filter2);


                ////Fill ItemName & ItemCode columns in retrieving order 
                //if (dataGridView1.Rows.Count > 0)
                //{
                //    for (int currentRow = 0; currentRow < dataGridView1.Rows.Count - 1; currentRow++)
                //    {
                //        int productItemId = Int32.Parse(dataGridView1.Rows[currentRow].Cells[idDataGridViewTextBoxColumn.Index].Value.ToString());
                //        GetItemDetailsByItemId(currentRow, productItemId);
                //    }

                //}


            }

        }

        private void SearchCodeBtn_Click(object sender, EventArgs e)
        {
            int projectId = 0;
            var storeId = GetSelectedStoreId();


            var filter = new PredicateExpression();
            if (storeId > 0)
            {
                filter.Add(StoreShelfBalanceFields.StoreId == storeId);
            }

            if (!string.IsNullOrWhiteSpace(txtProjectCode.Text))
            {
                var project = _projects.Cast<ProjectEntity>().FirstOrDefault(x => x.Code == txtProjectCode.Text);
                if (project != null)
                {
                    projectId = project.Id;
                    filter.AddWithAnd(StoreShelfBalanceFields.ProjectId == projectId);
                }
            }


            var itemPickerForm = new ItemPickerForm(1, 0, filter);
            if (itemPickerForm.ShowDialog() == DialogResult.OK)
            {
                if (itemPickerForm.SelectedItemId == 0)
                    return;

                var filter2 = new RelationPredicateBucket(StoreShelfBalanceFields.ItemId == itemPickerForm.SelectedItemId);
                filter2.Relations.Add(StoreShelfBalanceEntity.Relations.ShelfEntityUsingShelfId);
                filter2.PredicateExpression.AddWithAnd(filter);
                StoreShelfBalance.Clear();
                DALHelper.FetchCollection(StoreShelfBalance, filter2);



                ////Fill ItemName & ItemCode columns in retrieving order 
                //if (dataGridView1.Rows.Count > 0)
                //{
                //    for (int currentRow = 0; currentRow < dataGridView1.Rows.Count - 1; currentRow++)
                //    {
                //        int productItemId = Int32.Parse(dataGridView1.Rows[currentRow].Cells[idDataGridViewTextBoxColumn.Index].Value.ToString());
                //        GetItemDetailsByItemId(currentRow, productItemId);
                //    }
                //}

            }

        }


        private void GetItemDetailsByItemId(int rowIndex, int itemId)
        {
            DataTable itemDT = Business.GetItemDetails(itemId);
            if (itemDT.Rows.Count <= 0)
                return;

            dataGridView1.Rows[rowIndex].Cells[ItemCode.Index].Value = itemDT.Rows[0][0].ToString();
            dataGridView1.Rows[rowIndex].Cells[ItemName.Index].Value = itemDT.Rows[0][1].ToString();
            dataGridView1.Rows[rowIndex].Cells[idDataGridViewTextBoxColumn.Index].Value = itemId;

            return;
        }

        /// <summary>
        /// Called before generic save
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveBtn_Click(object sender, EventArgs e)
        {
            //try
            //{
                if (string.IsNullOrWhiteSpace(txtProjectCode.Text) || dataGridView1.Rows.Count == 0)
                {
                    MessageBox.Show("من فضلك استكمل البيانات");
                    return;
                }

                var storeId = GetSelectedStoreId();

                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    // last row for addition so no data in it
                    if (row.Index == dataGridView1.Rows.Count - 1) break;



                    var itemId = (int)row.Cells[ItemId.Index].Value;
                    var initialPrice = (decimal)row.Cells[UnitPrice.Index].Value;
                    var initialBalance = (decimal)row.Cells[balanceDataGridViewTextBoxColumn.Index].Value;

                    // Save in InitialBalance Table and StoreShelfBalance
                   // var initialBalanceEntity = new InitialBalanceEntity();
                    EntityCollection<StoreShelfBalanceEntity> StoreShelfBalanceExist = new EntityCollection<StoreShelfBalanceEntity>();
                    RelationPredicateBucket filterstoreshelf = new RelationPredicateBucket();
                    filterstoreshelf.PredicateExpression.AddWithAnd(StoreShelfBalanceFields.ShelfId== (int)row.Cells[shelfdIdDataGridViewTextBoxColumn.Index].Value);
                    filterstoreshelf.PredicateExpression.AddWithAnd(StoreShelfBalanceFields.ProjectId == GetSelectedProjectId());
                    filterstoreshelf.PredicateExpression.AddWithAnd(StoreShelfBalanceFields.ItemId == itemId);
                    filterstoreshelf.PredicateExpression.AddWithAnd(StoreShelfBalanceFields.StoreId == storeId);
                    DALHelper.FetchCollection(StoreShelfBalanceExist, filterstoreshelf);

                    if (StoreShelfBalanceExist.Count > 0)
                    {
                        StoreShelfBalanceExist[0].UnitPrice = initialPrice;
                        StoreShelfBalanceExist[0].Balance = initialBalance;
                        DALHelper.SaveCollection(StoreShelfBalanceExist);
                    }
                    else
                    {


                        var storeshelfbalanceEntity = new StoreShelfBalanceEntity();


                        // initialBalanceEntity.StoreId = storeId;
                        storeshelfbalanceEntity.StoreId = storeId;



                        //  initialBalanceEntity.ItemId = itemId;
                        //  initialBalanceEntity.ProjectId = (int)row.Cells[projectIdDataGridViewTextBoxColumn.Index].Value;
                        //  initialBalanceEntity.ShelfId = (int)row.Cells[shelfdIdDataGridViewTextBoxColumn.Index].Value;
                        storeshelfbalanceEntity.ItemId = itemId;
                        storeshelfbalanceEntity.ShelfId = (int)row.Cells[shelfdIdDataGridViewTextBoxColumn.Index].Value;
                        storeshelfbalanceEntity.ProjectId = GetSelectedProjectId();
                        //   initialBalanceEntity.UnitPrice = initialPrice;
                        storeshelfbalanceEntity.UnitPrice = initialPrice;
                        //    initialBalanceEntity.Balance = initialBalance;
                        storeshelfbalanceEntity.Balance = initialBalance;

                        // if saved then go to next iteration else also go to next iteration as it will be a existing item
                        //     DALHelper.SaveEntity(initialBalanceEntity, true);

                        DALHelper.SaveEntity(storeshelfbalanceEntity, true);
                    }
                }
            /*}
            catch(Exception ex)
            {
                MessageBox.Show("لم يتم الحفظ");
            }*/
        }

        private void SearchProjectBtn_Click(object sender, EventArgs e)
        {
            ResetTransactionItems();

                var filter = new RelationPredicateBucket();
                filter.PredicateExpression.Add(ProjectFields.IsGeneral == true);
                var searchForm = new SearchForm(ProjectFields.Code, ProjectFields.Name, ProjectFields.ActualStartDate, filter,
                                                () => DALHelper.GetDynamicList(ProjectFields.Id, ProjectFields.Name, null));


            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                txtProjectCode.Text = searchForm.SelectedNumber;
            }


        }

        private void SearchStoresBtn_Click(object sender, EventArgs e)
        {
            //var searchForm = new fromGeneralEntityPicker("Store");

            //        FormsHelper.LoadComboBox(StoresDDL, StoreFields.Id, StoreFields.Name, () => DALHelper.GetDynamicList(StoreFields.Id, StoreFields.Name, null));
            //    else
            //        FormsHelper.LoadComboBox(StoresDDL, StoreFields.Id, StoreFields.Name, () => Business.GetStoresWithoutTransactions());

            //SearchForm searchform;
            //if (IsAdmin)
            //    searchform = new SearchForm(StoreFields.Code, StoreFields.Name, null, null,
            //                                        () => DALHelper.GetDynamicList(StoreFields.Id, StoreFields.Name, null));
            //else
            //    searchform = new SearchForm(StoreFields.Code, StoreFields.Name, null, null,
            //                                                   () => Business.GetStoresWithoutTransactions());

            var searchForm = new fromGeneralEntityPicker("Store");
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                StoresTB.Text = searchForm.SelectedItemCode;

            }

        }

        private void StoresTB_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(StoresTB.Text))
            {
                DataTable DTStore = Business.GetStoreDetails(StoresTB.Text);
                if (DTStore.Rows.Count > 0)
                {
                    lblStoreName.Text = DTStore.Rows[0][2].ToString();

                    ResetTransactionItems();

                    GetShelves();

                }
                else
                {
                    lblStoreName.Text = string.Empty;
                    //RunBtn.Enabled = false;
                }
            }
            else
            {
                lblStoreName.Text = string.Empty;
                //RunBtn.Enabled = false;
            }
        }
    }
}
